#!/bin/bash

this_path=$(dirname $(realpath $0))
repo_path=$(dirname ${this_path})
tmpworkdir=/tmp/envsetup.$RANDOM

# Function to display help information
show_help() {
  echo "Usage: $(basename $0) [OPTIONS]"
  echo "Description: Build a Docker image from a Dockerfile."
  echo
  echo "Options:"
  echo "  -h          Display this help message and exit."
  echo "  -d PATH     required, Specify the path of Dockerfile"
  echo "  -t TAG      required, Specify the tag for the built image."
  echo "  -i init.sh  required, Specify the init script"
  echo "  -u uid      required, Specify the uid in host"
  echo "  -U USERNAME optional, Specify the username"
}

# Initialize default values
path=""
tag=""
init_script=""
userid=""
username=""

# Use getopts to parse command line options
while getopts "d:t:i:u:U:h" opt; do
  case $opt in
    d)
      path=$OPTARG
      ;;
    t)
      tag=$OPTARG
      ;;
    i)
      init_script=$OPTARG
      ;;
    u)
      userid=$OPTARG
      ;;
    U)
      username=$OPTARG
      ;;
    h)
      show_help
      exit 0
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

# Shift non-option arguments
shift $((OPTIND-1))

# echo "Path: $path"
# echo "Username: $username"
# echo "Remaining arguments: $@"

if [[ -z "$path" ]]; then
  echo "Error: Dockerfile path is required."
  exit 1
fi

if [[ -z "$tag" ]]; then
  echo "Error: Tag is required."
  exit 1
fi

if [[ -z "$init_script" ]]; then
  echo "Error: Init script is required."
  exit 1
fi

if [[ -z "$userid" ]]; then
  echo "Error: uid is required."
  exit 1
fi

set -e

trap "\\rm -fr ${tmpworkdir}" EXIT

mkdir -p ${tmpworkdir}
cd ${repo_path} && tar -czf ${tmpworkdir}/envsetup.tar.gz ./* || true; cd -

cp -f ${path}/Dockerfile ${tmpworkdir}

if [[ -n "${username}" ]]; then
  sed -i "s%^ARG user=.*%ARG user=${username}%g" ${tmpworkdir}/Dockerfile
else
  username=$(grep '^ARG user=.*' ${tmpworkdir}/Dockerfile | cut -d = -f 2)
fi

source ${init_script}

set -x
docker build -t ${tag} ${tmpworkdir}
